package com.sxfq.loansupermarket.backsystem.modular.tcCenter.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.TcInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantResListInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.SearchConsultantResListInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantResListService;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/reserve")
public class ConsultantResListController extends BaseController {
    @Autowired
    IConsultantResListService service;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    ICustomerService customerService;

    @Autowired
    IConsultantService consultantService;

    @Autowired
    IReservationsService reservationsService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/tcCenter/consultant/";

    /**
     * 跳转到预约回访
     */
    @RequestMapping("")
    public String reserve(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "consultant_reserve.html";
    }

    /**
     * 预约客户管理列表
     */
    @RequestMapping("/resList")
    @ResponseBody
    public Object resInfoList(SearchConsultantResListInfo info, HttpServletRequest request) {
        Page<ConsultantResListInfo> page = new PageFactory<ConsultantResListInfo>().defaultPage();
        try {
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<ConsultantResListInfo> list = service.selectPageListByQuery(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = service.selectPageListByQuery(page, info);
            }
            page.setTotal(service.getQueryPagesCount(page, info));
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 统计查询 预约回访 人数
     */
    @RequestMapping(value = "/totalNum", method = RequestMethod.GET)
    @ResponseBody
    public List<ConsultantInfo> changeNum(String param1, String param2, String param3,
                                          String param4, String param5, String param6, String param7, String param8, String param9) throws Exception {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        String tableName = tableHead + "customer_info";
        String contitionInfo = "";
        if (StringUtils.isNotBlank(param3)) {
            contitionInfo += " and t.follow_status <= '" + param3 + "' ";
        }
        if (StringUtils.isNotBlank(param4)) {
            contitionInfo += " and t.consumption_status = '" + param4 + "' ";
        }
        if (StringUtils.isNotBlank(param5)) {
            contitionInfo += " and t.query_tc = '" + param5 + "' ";
        }
        if (StringUtils.isNotBlank(param6)) {
            contitionInfo += " and t.deal_status = '" + param6 + "' ";
        }
        if (StringUtils.isNotBlank(param7)) {
            contitionInfo += " and t.diagnosis_status = '" + param7 + "' ";
        }
        if (StringUtils.isNotBlank(param6)) {
            contitionInfo += " and (t.customer_name like CONCAT('%','" + param8 + "','%') or t.customer_phone like CONCAT('%','" + param8 + "','%')  or " +
                    " t.wechat_number like CONCAT('%','" + param8 + "','%') or t.medical_record_number like CONCAT('%','" + param8 + "','%') or t.szm like CONCAT('%" + param8 + "%')" +
                    " or t.customer_phone2 like CONCAT('%" + param8 + "%')) ";
        }
        String doneSql = "";
        String notDoneSql = "";
        if (StringUtils.isNotBlank(param5)) {  // 1待回访 2已回访
            doneSql += " and t3.revisit = '" + param5 + "'";
            doneSql += " and !(t.follow_status='跟踪结束' or t.follow_status='跟踪完成')";
            if (StringUtils.isNotBlank(param1)) {
                doneSql += " and t.appointment_time >= '" + param1 + "' ";
            }
            if (StringUtils.isNotBlank(param2)) {
                doneSql += " and t.appointment_time <= '" + param2 + "'  ";
            }
            notDoneSql += " and t3.revisit = '" + param5 + "'";
            if (StringUtils.isNotBlank(param1)) {
                notDoneSql += " and t3.revisit_time >= '" + param1 + "' ";
            }
            if (StringUtils.isNotBlank(param2)) {
                notDoneSql += " and t3.revisit_time <= '" + param2 + "'  ";
            }
        } else {
            doneSql += " and !(t.follow_status='跟踪结束' or t.follow_status='跟踪完成')";
            if (StringUtils.isNotBlank(param1)) {
                doneSql += " and t.appointment_time >= '" + param1 + "' ";
            }
            if (StringUtils.isNotBlank(param2)) {
                doneSql += " and t.appointment_time <= '" + param2 + "'  ";
            }
            if (StringUtils.isNotBlank(param1)) {
                notDoneSql += " and t3.revisit_time >= '" + param1 + "' ";
            }
            if (StringUtils.isNotBlank(param2)) {
                notDoneSql += " and t3.revisit_time <= '" + param2 + "'  ";
            }
        }
        String sql = " select count(*) as countNum from(select t.id from " + tableName + " t " +
                "left join return_visit_info t3 on t.reservations_id =t3.reservations_id " +
                "where 1=1 " + doneSql + " "
                + contitionInfo + " group by t.reservations_id ) bb " +
                " union all select count(*) as countNum from(select t.id from " + tableName + " t " +
                "left join return_visit_info t3 on t.reservations_id =t3.reservations_id " +
                " where 1=1 " + notDoneSql + " "
                + contitionInfo + " group by t.reservations_id ) bb ";
        List<ConsultantInfo> infoList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return infoList;
    }

    @RequestMapping(value = "/consultantExport")
    public void consultantExport(@RequestParam(required = false) String startAppointmentTime,
                                 @RequestParam(required = false) String endAppointmentTime,
                                 @RequestParam(required = false) String reach,
                                 @RequestParam(required = false) String diagnosisStatus,
                                 @RequestParam(required = false) String fieldTc,
                                 @RequestParam(required = false) String dealStatus,
                                 @RequestParam(required = false) String consumptionStatus,
                                 @RequestParam(required = false) String followStatus, HttpServletResponse response) {
        try {
            SearchConsultantResListInfo searchInfo = new SearchConsultantResListInfo();
            searchInfo.setReach(reach);
            searchInfo.setConsumptionStatus(consumptionStatus);
            searchInfo.setFollowStatus(followStatus);
            searchInfo.setStartAppointmentTime(startAppointmentTime);
            searchInfo.setEndAppointmentTime(endAppointmentTime);
            searchInfo.setFieldTc(fieldTc);
            searchInfo.setDiagnosisStatus(diagnosisStatus);
            searchInfo.setDealStatus(dealStatus);
            List<ConsultantResListInfo> list = service.consultantExpor(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 19; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("客户状态");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("病历号");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("手机号");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("咨询项目");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("一级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("二级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("三级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("首次到店时间");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("到店时间");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("tc");
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue("开单状态");
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue("成交金额");
            cell.setCellStyle(style);
            cell = row.createCell(15);
            cell.setCellValue("欠费金额");
            cell.setCellStyle(style);
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                ConsultantResListInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                int customerAge = 0;
                if (map.getCustomerAge() != null) {
                    customerAge = map.getCustomerAge();
                }
                String medicalRecordNumber = map.getMedicalRecordNumber();
                String appointmentPayService = map.getAppointmentPayService();
                String arrivalTime = map.getArrivalTime();
                String customerStatus = "";
                if (map.getCustomerStatus() != null) {
                    customerStatus = map.getCustomerStatus();
                }
                String customerPhone = "";
                if (map.getCustomerPhone() != null) {
                    customerPhone = map.getCustomerPhone();
                }
                String customerName = "";
                if (map.getCustomerName() != null) {
                    customerName = map.getCustomerName();
                }
                String sex = "";
                if (map.getSex() != null) {
                    sex = map.getSex();
                }
                fieldTc = "";
                if (map.getFieldTc() != null) {
                    fieldTc = map.getFieldTc();
                }
                String oneChannel = map.getOneChannel();
                String twoChannel = map.getTwoChannel();
                String thrChannel = map.getThrChannel();
                String firstVisitDate = map.getFirstVisitDate();
                if (map.getDealStatus() != null) {
                    dealStatus = map.getDealStatus();
                }
                String actualAccountBalances = map.getActualAccountBalances();
                if (StringUtil.isEmpty(actualAccountBalances)) {
                    actualAccountBalances = "0.00";
                }
                String accountArrearss = map.getAccountArrearss();
                if (StringUtil.isEmpty(accountArrearss)) {
                    accountArrearss = "0.00";
                }
                String id = map.getId();
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 15; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(customerStatus);
                row.getCell(1).setCellValue(medicalRecordNumber);
                row.getCell(2).setCellValue(customerName);
                row.getCell(3).setCellValue(sex);
                row.getCell(4).setCellValue(customerAge);
                row.getCell(5).setCellValue(customerPhone);
                row.getCell(6).setCellValue(appointmentPayService);
                row.getCell(7).setCellValue(oneChannel);
                row.getCell(8).setCellValue(twoChannel);
                row.getCell(9).setCellValue(thrChannel);
                row.getCell(10).setCellValue(firstVisitDate);
                row.getCell(11).setCellValue(arrivalTime);
                row.getCell(12).setCellValue(fieldTc);
                row.getCell(13).setCellValue(dealStatus);
                row.getCell(14).setCellValue(actualAccountBalances);
                row.getCell(15).setCellValue(accountArrearss);
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}